package com.gxg.dao;

import com.gxg.entities.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao
{
  @Autowired
  private JdbcTemplate jdbcTemplate;
  
  public Boolean isUser(String id)
  {
    int rowCount = ((Integer)this.jdbcTemplate.queryForObject("select count(*) from User where id=?", Integer.class, new Object[] { id })).intValue();
    if (rowCount == 0) {
      return Boolean.valueOf(false);
    }
    return Boolean.valueOf(true);
  }
  
  public User getUser(String id)
  {
    if (isUser(id).booleanValue())
    {
      String sql = "select * from User where id=?";
      User user = (User)this.jdbcTemplate.queryForObject(sql, new RowMapper()
      {
        public User mapRow(ResultSet resultSet, int i)
          throws SQLException
        {
          User user = new User();
          user.setId(resultSet.getString("id"));
          user.setPassword(resultSet.getString("password"));
          user.setEmail(resultSet.getString("email"));
          user.setName(resultSet.getString("name"));
          user.setRole(resultSet.getString("role"));
          user.setSex(resultSet.getString("sex"));
          user.setTel(resultSet.getString("tel"));
          return user;
        }
      }, new Object[] { id });
      
      return user;
    }
    return null;
  }
  
  public void updatePasswordById(String password, String id)
  {
    String sql = "update User set password=? where id=?";
    this.jdbcTemplate.update(sql, new Object[] { password, id });
  }
  
  public void insertUser(User user)
  {
    String sql = "insert into User values(?,?,?,?,?,?,?)";
    this.jdbcTemplate.update(sql, new Object[] { user.getId(), user.getPassword(), user.getName(), user.getSex(), user.getEmail(), user.getTel(), user.getRole() });
  }
  
  public void updateUserById(User user)
  {
    String sql = "update User set name=?, sex=?, tel=?, email=? where id=?";
    this.jdbcTemplate.update(sql, new Object[] { user.getName(), user.getSex(), user.getTel(), user.getEmail(), user.getId() });
  }
}
